<?php
/**
 * 描述
 * Created by Paco
 * Date: 2019/1/25 Time: 16:02
 */

namespace App\Repositories\Shop;


use App\Models\Log\LogShop;
use App\Models\Shop;
use App\Repositories\Repository;
use Illuminate\Support\Facades\DB;

class AdminShopRepository extends Repository
{
    public function index($params)
    {
        $shops = Shop::query()->when(!empty($params['shop_name']), function ($query) use ($params) {
            $query->where('shop_name', 'like', '%' . $params['shop_name'] . '%');
        })->orderBy('updated_at', 'desc')
            ->paginate($this->page_size, ['*'], 'page', $this->page);
        return $this->respondWith($shops);
    }

    public function shop($params)
    {
        $shops = LogShop::query()->when(!empty($params['shop_name']), function ($query) use ($params) {
            $query->where('shop_name', 'like', '%' . $params['shop_name'] . '%');
        })->orderBy('updated_at', 'desc')
            ->paginate($this->page_size, ['*'], 'page', $this->page);

        foreach ($shops as $k=>$shop){
            if($shop->busniess_license){
                $shops[$k]->busniess_license = json_decode($shop->busniess_license,true);
            }
            if($shop->trademark){
                $shops[$k]->trademark = json_decode($shop->trademark,true);
            }

            if($shop->environment_protection){
                $shops[$k]->environment_protection = json_decode($shop->environment_protection,true);
            }

        }

        return $this->respondWith($shops);
    }

    public function update($params)
    {
        $shop = LogShop::query()->find($params['shop_id']);
        if (!$shop) {
            return $this->respondError(10109);
        }
        DB::beginTransaction();
        try {
            if ((isset($params['checked']) && $params['checked'] == 1) || isset($params['status'])) {
                $realshop = Shop::query()->find($params['shop_id']);
                $realshop->fill($params)->save();
            }
            $shop->fill($params)->save();
            DB::commit();
            return $this->respondSuccess();
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->respondError(10108);
        }
    }
}